package com.project.dev.ouestpaul;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.Document;

import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.Toast;
import android.provider.Settings;

public class ItineraireActivity extends FragmentActivity implements
		LocationListener, OnClickListener {

	private GoogleMap gMap;
	private double X;
	private double Y;
	private String titre;
	LatLng CoordRecherche;
	private Marker marker;
	private Marker markerPosition;
	private LocationManager locationManager;
	private String provider;
	private Polyline newPolyline;
	private int width, height;
	LatLng coordLocation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map);
		
		Bundle objetbunble  = this.getIntent().getExtras();
        if (objetbunble != null && objetbunble.containsKey("X") && objetbunble.containsKey("Y")) {
        	X = this.getIntent().getDoubleExtra("X", X);
            Y = this.getIntent().getDoubleExtra("Y", Y);
            titre = this.getIntent().getStringExtra("titre");
        }else {
        	//Erreur
        	X = 0;
        	Y = 0;
        	titre = "erreur";
        }
        CoordRecherche = new LatLng(X, Y);
		
	    try {
	    	initilizeMap();
	    } 
	    catch (Exception e) {
	            e.printStackTrace();
	    }
	    
	    marker = gMap.addMarker(new MarkerOptions().title(titre).position(CoordRecherche));
		
		LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabledGPS = service
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean enabledWiFi = service
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!enabledGPS) {
            Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
            /*Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);*/
        }


        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            Toast.makeText(this, "Selected Provider " + provider,
                    Toast.LENGTH_SHORT).show();
            onLocationChanged(location);
        } else {
        	Toast.makeText(this, "Impossible de vous localiser",
                    Toast.LENGTH_SHORT).show();
        	locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, (android.location.LocationListener) this);
        }
        
        
		double lat = location.getLatitude();
		double lng = location.getLongitude();
		coordLocation = new LatLng(lat, lng);
        
		ImageButton bMoins = (ImageButton) findViewById(R.id.imageButton2);
		bMoins.setOnClickListener(this);
		ImageButton bPlus = (ImageButton) findViewById(R.id.imageButton1);
		bPlus.setOnClickListener(this);
		ImageButton bLocation = (ImageButton) findViewById(R.id.ImageButton01);
		bLocation.setOnClickListener(this);
        
        findDirections(location.getLatitude(), location.getLongitude(), CoordRecherche.latitude, CoordRecherche.longitude, GMapV2Direction.MODE_DRIVING);
 
			
	}

	private void initilizeMap() {
		if (gMap == null) {
			gMap = ((SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.map)).getMap();
			gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
			CameraPosition cameraPosition = new CameraPosition.Builder()
					.target(CoordRecherche) // Sets the center of the map to
											// Mountain View
					.zoom(16) // Sets the zoom
					// .bearing(90) // Sets the orientation of the camera to
					// east
					.tilt(30) // Sets the tilt of the camera to 30 degrees
					.build(); // Creates a CameraPosition from the builder
			gMap.animateCamera(CameraUpdateFactory
					.newCameraPosition(cameraPosition));
			gMap.getUiSettings().setZoomGesturesEnabled(false);
			gMap.getUiSettings().setZoomControlsEnabled(false);
			gMap.getUiSettings().setMyLocationButtonEnabled(false);
			gMap.getUiSettings().setCompassEnabled(false);
			gMap.setBuildingsEnabled(true);
			gMap.setMyLocationEnabled(true);

			if (gMap == null) {
				Toast.makeText(getApplicationContext(),
						"Sorry! unable to create maps", Toast.LENGTH_SHORT)
						.show();
			}
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.itineraire, menu);
		return true;
	}

	@Override
	public void onLocationChanged(Location location) {
		double lat = location.getLatitude();
		double lng = location.getLongitude();
		LatLng coordinate = new LatLng(lat, lng);
		markerPosition = gMap.addMarker(new MarkerOptions()
				.position(coordinate)
				.title("Start")
				.snippet("Vous etes ici"));
	}

	public void onProviderDisabled(String provider) {
		Toast.makeText(this, "Enabled new provider " + provider,
				Toast.LENGTH_SHORT).show();

	}

	public void onProviderEnabled(String provider) {
		Toast.makeText(this, "Disabled provider " + provider,
				Toast.LENGTH_SHORT).show();

	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}
	
	@Override
	protected void onResume() {
		
		super.onResume();

	}

	public void handleGetDirectionsResult(ArrayList<LatLng> directionPoints) {
		PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.BLUE);

		for(int i = 0 ; i < directionPoints.size() ; i++) 
		{          
			rectLine.add(directionPoints.get(i));
		}
		if (newPolyline != null)
		{
			newPolyline.remove();
		}
		newPolyline = gMap.addPolyline(rectLine);
		
	}
	
	@SuppressWarnings("deprecation")
	private void getSreenDimanstions()
	{
		Display display = getWindowManager().getDefaultDisplay();
		width = display.getWidth(); 
		height = display.getHeight(); 
	}
	
	private LatLngBounds createLatLngBoundsObject(LatLng firstLocation, LatLng secondLocation)
	{
		if (firstLocation != null && secondLocation != null)
		{
			LatLngBounds.Builder builder = new LatLngBounds.Builder();    
			builder.include(firstLocation).include(secondLocation);
			
			return builder.build();
		}
		return null;
	}
	
	public void findDirections(double fromPositionDoubleLat, double fromPositionDoubleLong, double toPositionDoubleLat, double toPositionDoubleLong, String mode)
	{
		Map<String, String> map = new HashMap<String, String>();
		map.put(GetDirectionsAsyncTask.USER_CURRENT_LAT, String.valueOf(fromPositionDoubleLat));
		map.put(GetDirectionsAsyncTask.USER_CURRENT_LONG, String.valueOf(fromPositionDoubleLong));
		map.put(GetDirectionsAsyncTask.DESTINATION_LAT, String.valueOf(toPositionDoubleLat));
		map.put(GetDirectionsAsyncTask.DESTINATION_LONG, String.valueOf(toPositionDoubleLong));
		map.put(GetDirectionsAsyncTask.DIRECTIONS_MODE, mode);
		
		GetDirectionsAsyncTask asyncTask = new GetDirectionsAsyncTask(this);
		asyncTask.execute(map);	
	}

	@Override
	public void onClick(View v) {
		float z = gMap.getCameraPosition().zoom;
		LatLng coordActu;
		switch (v.getId()) {
		case R.id.imageButton1:
			coordActu = gMap.getCameraPosition().target;

			CameraPosition updateZoom = new CameraPosition.Builder()
				.target(coordActu).zoom(z + 1).tilt(30).build();
			gMap.animateCamera(CameraUpdateFactory
					.newCameraPosition(updateZoom));
			break;
		case R.id.imageButton2:
			coordActu = gMap.getCameraPosition().target;
			CameraPosition updateDezoom = new CameraPosition.Builder()
				.target(coordActu).zoom(z - 1).tilt(30).build();
			gMap.animateCamera(CameraUpdateFactory
					.newCameraPosition(updateDezoom));
			break;
		case R.id.ImageButton01:
			CameraPosition update = new CameraPosition.Builder()
				.target(coordLocation).zoom(z).tilt(30).build();
			gMap.animateCamera(CameraUpdateFactory
					.newCameraPosition(update));
			break;
		default:
			break;
		}
		
	}
	


}
